<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html><head><title>Programming in Lua : 8</title>
<link rel="stylesheet" type="text/css" href="pil.css">
</head>
<body>
<p class="warning">
<A HREF="contents.html"><IMG TITLE="Programming in Lua (first edition)" SRC="capa.jpg" ALT="" ALIGN="left"></A>This first edition was written for Lua 5.0. While still largely relevant for later versions, there are some differences.<BR>The third edition targets Lua 5.2 and is available at <A HREF="http://www.amazon.com/exec/obidos/ASIN/859037985X/theprogrammil3-20">Amazon</A> and other bookstores.<BR>By buying the book, you also help to <A HREF="../donations.html">support the Lua project</A>.
</p>
<table width="100%" class="nav">
<tr>
<td width="10%" align="left"><a href="7.5.html"><img border="0" src="left.png" alt="Previous"></a></td>
<td width="80%" align="center"><a href="contents.html"><font face="Helvetica,Arial,sanserif">
<font color="gray">Programming in </font><font color="blue"> Lua</font>
</font></a></td>
<td width="10%" align="right"><a href="8.1.html"><img border="0" src="right.png" alt="Next"></a></td>
</tr>
<tr>
<td width="10%" align="left"></td>
<td width="80%" align="center"><a href="contents.html#P1">Part I. The Language</a>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<a href="contents.html#8">Chapter 8. Compilation, Execution, and Errors</a></td>
<td width="10%" align="right"></td></tr>
</table>
<hr/>
<h1>8 &ndash; Compilation, Execution, and Errors</h1>

<p>

<p>Although we refer to Lua as an interpreted language,
Lua always precompiles source code to an
intermediate form before running it.
(This is not a big deal:
Most interpreted languages do the same.)
The presence of a compilation phase may sound out of place in
an interpreted language like Lua.
However, the distinguishing feature of interpreted languages
is not that they are not compiled,
but that any compiler is part of the language runtime
and that, therefore, it is possible (and easy) to execute
code generated on the fly.
We may say that the presence of a function
like <code>dofile</code> is what allows Lua
to be called an interpreted language.

<p>Previously, we introduced <code>dofile</code> as a kind of primitive
operation to run chunks of Lua code.
The <code>dofile</code> function is actually an auxiliary function;
<code>loadfile</code> does the hard work.
Like <code>dofile</code>, <code>loadfile</code>
also loads a Lua chunk from a file,
but it does not run the chunk.
Instead, it only compiles the chunk
and returns the compiled chunk as a function.
Moreover, unlike <code>dofile</code>,
<code>loadfile</code> does not raise errors,
but instead returns error codes,
so that we can handle the error.
We could define <code>dofile</code> as follows:
<pre>
    function dofile (filename)
      local f = assert(loadfile(filename))
      return f()
    end
</pre>
Note the use of <code>assert</code> to raise an error if <code>loadfile</code> fails.

<p>For simple tasks,
<code>dofile</code> is handy, as it does the whole job in one call.
However, <code>loadfile</code> is more flexible.
In case of errors, <code>loadfile</code> returns <B>nil</B> plus the error message,
which allows us to handle the error in customized ways.
Moreover, if we need to run a file several times,
we can call <code>loadfile</code> once and
call its result several times.
This is much cheaper than several calls to <code>dofile</code>,
because the program compiles the file only once.

<p>The <code>loadstring</code> function is similar to <code>loadfile</code>,
except that it reads its chunk from a string,
not from a file.
For instance, after the code
<pre>
    f = loadstring("i = i + 1")
</pre>
<code>f</code> will be a function that,
when invoked, executes <code>i = i + 1</code>:
<pre>
    i = 0
    f(); print(i)   --> 1
    f(); print(i)   --> 2
</pre>
The <code>loadstring</code> function is powerful;
it must be used with care.
It is also an expensive function (when compared to its alternatives)
and may result in incomprehensible code.
Before you use it, make sure that there is no simpler way
to solve the problem at hand.

<p>Lua treats any independent chunk
as the body of an anonymous function.
For instance, for the chunk <code>"a = 1"</code>,
<code>loadstring</code> returns the equivalent of
<pre>
    function () a = 1 end
</pre>
Like any other function,
chunks can declare local variables and return values:
<pre>
    f = loadstring("local a = 10; return a + 20")
    print(f())          --> 30
</pre>

<p>Both <code>loadstring</code> and <code>loadfile</code> never raise errors.
In case of any kind of error,
both functions return <B>nil</B> plus an error message:
<pre>
    print(loadstring("i i"))
      --> nil     [string "i i"]:1: `=' expected near `i'
</pre>
Moreover, both functions never have any
kind of side effect.
They only compile the chunk to an internal representation
and return the result,
as an anonymous function.
A common mistake is to assume that <code>loadfile</code>
(or <code>loadstring</code>) defines functions.
In Lua, function definitions are assignments;
as such, they are made at runtime, not at compile time.
For instance, suppose we have a file <code>foo.lua</code> like this:
<pre>
    -- file `foo.lua'
    function foo (x)
      print(x)
    end
</pre>
We then run the command
<pre>
    f = loadfile("foo.lua")
</pre>
After this command, <code>foo</code> is compiled, but it is not defined yet.
To define it, you must run the chunk:
<pre>
    f()           -- defines `foo'
    foo("ok")     --> ok
</pre>

<p>If you want to do a quick-and-dirty <code>dostring</code>
(i.e., to load and run a chunk) you may call the result from
<code>loadstring</code> directly:
<pre>
    loadstring(s)()
</pre>
However, if there is any syntax error,
<code>loadstring</code> will return <B>nil</B>
and the final error message will be an
<code>"attempt to call a nil value"</code>.
For clearer error messages, use <code>assert</code>:
<pre>
    assert(loadstring(s))()
</pre>

<p>Usually, it does not make sense to use <code>loadstring</code>
on a literal string.
For instance, the code
<pre>
    f = loadstring("i = i + 1")
</pre>
is roughly equivalent to
<pre>
    f = function () i = i + 1 end
</pre>
but the second code is much faster,
because it is compiled only once,
when the chunk is compiled.
In the first code,
each call to <code>loadstring</code> involves a new compilation.
However, the two codes are not completely equivalent,
because <code>loadstring</code> does not compile with lexical scoping.
To see the difference, let us change the previous examples a little:
<pre>
    local i = 0
    f = loadstring("i = i + 1")
    g = function () i = i + 1 end
</pre>
The <code>g</code> function manipulates the local <code>i</code>, as expected,
but <code>f</code> manipulates a global <code>i</code>,
because <code>loadstring</code> always compiles its strings in a global
environment.

<p>The most typical use of <code>loadstring</code> is to run external code,
that is, pieces of code that come from outside your program.
For instance, you may want to plot a function defined by the user;
the user enters the function code
and then you use <code>loadstring</code> to evaluate it.
Note that <code>loadstring</code> expects a chunk, that is, statements.
If you want to evaluate an expression,
you must prefix it with <b>return</b>,
so that you get a statement that returns the value of the given expression.
See the example:
<pre>
    print "enter your expression:"
    local l = io.read()
    local func = assert(loadstring("return " .. l))
    print("the value of your expression is " .. func())
</pre>

<p>The function returned by <code>loadstring</code> is a regular function,
so you can call it several times:
<pre>
    print "enter function to be plotted (with variable `x'):"
    local l = io.read()
    local f = assert(loadstring("return " .. l))
    for i=1,20 do
      x = i   -- global `x' (to be visible from the chunk)
      print(string.rep("*", f()))
    end
</pre>

<p>In a production-quality program that needs to run external code,
you should handle any errors reported by <code>loadstring</code>.
Moreover, if the code cannot be trusted,
you may want to run the new chunk in a protected environment,
to avoid unpleasant side effects when running the code.

<hr/>
<table width="100%" class="nav">
<tr valign="top">
<td width="90%" align="left">
<small>
  Copyright &copy; 2003&ndash;2004 Roberto Ierusalimschy.  All rights reserved.
</small>
</td>
<td width="10%" align="right"><a href="8.1.html"><img border="0" src="right.png" alt="Next"></a></td>
</tr>
</table>


</body></html>

